<?php
error_reporting(0);
include_once "src/controller/dbmanagement/DBConnection.php";
include_once "src/rrsexception/DBException.php";
include_once "src/rrsexception/DBConnectionException.php";
include_once "src/model/Reservation.php";
/*
 * This class inserts, updates and dispalys records from the tReservation table
 *
*/


class ReservationDBManagement {

    /**
     *Precondition:  Accepts a reservation object: UserID and ResourceID
     *               member attribute MUST be set
     *Postcondition: Inserts a record into the tReservation table and returns
     *               true if successful and false otherwise.
     **/
    public static function insertReservation($reservation) {
        try {

            if (!ReservationDBManagement::isReoccurrentResourceReservationValid($reservation->getResourceID(),
                    $reservation->getStartDate(), $reservation->getEndDate(), $reservation->getReOccurrenceID(), $reservation->getStopDate())) {
                return false;
            }

            $cnn = new DBConnection();

            $ResourceID = $reservation->getResourceID();
            $StartDate = $reservation->getStartDate();
            $EndDate = $reservation->getEndDate();
            $UserID = $reservation->getUserID();
            $ReOccurrenceID = $reservation->getReOccurrenceID();
            $StopDate = $reservation->getStopDate();
            if (!isset($ReOccurrenceID) || $ReOccurrenceID == '') {
                $query = "INSERT INTO tReservation (Resource_id,
                                                        Start_date,
                                                        End_date,
                                                        User_id,
                                                        ReOccurrence_id,
                                                        Stop_date)
                              VALUES ('$ResourceID',
                                      '$StartDate',
                                      '$EndDate',
                                      '$UserID',
                                       NULL,
                                      NULL)";
            }
            else {
                $query = "INSERT INTO tReservation (Resource_id,
                                                        Start_date,
                                                        End_date,
                                                        User_id,
                                                        ReOccurrence_id,
                                                        Stop_date)
                              VALUES ('$ResourceID',
                                      '$StartDate',
                                      '$EndDate',
                                      '$UserID',
                                      '$ReOccurrenceID',
                                      '$StopDate')";

            }
            //echo $query;
            $cnn->execute($query);

            //Check if the record was successfully inserted
            $query = "SELECT * FROM tReservation
                          WHERE tReservation.Resource_id = '$ResourceID'
                          AND tReservation.Start_date = '$StartDate'
                          AND tReservation.End_date = '$EndDate'";

            $result = $cnn->execute($query);

            $numRows = mysql_numrows($result);

            if ($numRows == 0) {
                $cnn->disconnect();
                return false;
            }
            else {
                $cnn->disconnect();
                return true;
            }
        }
        catch (DBException $e) {
            throw $e;
        }
        catch (DBConnectionException $e) {
            throw $e;
        }
    }

    /**
     *Precondition:  Accepts a reservation object: The following attributes must be set:
     *                - Reservation_id
     *Postcondition: Deletes a record from the tReservation table and returns
     *               true if successful and false otherwise.
     **/
    public static function deleteReservationByID($reservation) {
        try {
            $cnn = new DBConnection();

            $ReservationID = $reservation->getReservationID();

            $query = "DELETE FROM tReservation WHERE Reservation_id = '$ReservationID'";

            $cnn->execute($query);

            //Check if the record was successfully deleted
            $query = "SELECT * FROM tReservation
                          WHERE tReservation.Reservation_id = '$ReservationID'";

            $result = $cnn->execute($query);

            $numRows = mysql_numrows($result);

            if ($numRows == 0) {
                $cnn->disconnect();
                return true;
            }
            else {
                $cnn->disconnect();
                return false;
            }
            $cnn->disconnect();
        }
        catch (DBException $e) {
            throw $e;
        }
        catch (DBConnectionException $e) {
            throw $e;
        }
    }

    /**
     *Precondition:  Accepts a reservation object: The following attributes must be set:
     *                - Resource_id
     *                - User_id
     *                - Reservation_id
     *Postcondition: updates record in the tReservation table by ReservationID
     *               No Boolean Value is returned.
     **/
    public static function updateReservationRecord($reservation) {

        try {
            $cnn = new DBConnection();

            $ReservationID = $reservation->getReservationID();
            $ResourceID = $reservation->getResourceID();
            $StartDate = $reservation->getStartDate();
            $EndDate = $reservation->getEndDate();
            $UserID = $reservation->getUserID();
            $ReOccurrenceID = $reservation->getReOccurrenceID();
            $StopDate = $reservation->getStopDate();
            if (!isset($ReOccurrenceID) || $ReOccurrenceID == '') {
                $query = "UPDATE tReservation SET Resource_id = '$ResourceID',
                                                      Start_date = '$StartDate',
                                                      End_date = '$EndDate',
                                                      User_id = '$UserID',
                                                      ReOccurrence_id = NULL,
                                                      Stop_date = '$StopDate'
                              WHERE Reservation_id = '$ReservationID'";
            }
            else {
                $query = "UPDATE tReservation SET Resource_id = '$ResourceID',
                                                      Start_date = '$StartDate',
                                                      End_date = '$EndDate',
                                                      User_id = '$UserID',
                                                      ReOccurrence_id = '$ReOccurrenceID',
                                                      Stop_date = '$StopDate'
                              WHERE Reservation_id = '$ReservationID'";
            }

            $cnn->execute($query);

            $cnn->disconnect();
        }
        catch (DBException $e) {
            throw $e;
        }
        catch (DBConnectionException $e) {
            throw $e;
        }
    }

    /**
     *Precondition:  Accepts a reservation object: The following attributes must be set:
     *                - Reservation_id
     *Postcondition: Find and return a specific reservation in the tReservation table
     *               otherwise return false
     **/
    public static function findSpecificReservation($Reservation) {
        try {
            $cnn = new DBConnection();
            $reservationRecord = new Reservation();
            $Reservation = $Reservation->getReservationID();
            $query = "SELECT * FROM tReservation WHERE Reservation_id = '$Reservation'";
            $result = $cnn->execute($query);

            $numRows = mysql_numrows($result);

            if ($numRows == 0) {
                $cnn->disconnect();
                return false;
            }
            else {
                $row = mysql_fetch_array($result);

                $reservationRecord->setResourceID($row['Resource_id']);
                $reservationRecord->setStartDate($row['Start_date']);
                $reservationRecord->setEndDate($row['End_date']);
                $reservationRecord->setUserID($row['User_id']);
                $reservationRecord->setReOccurrenceID($row['ReOccurrence_id']);
                $reservationRecord->setStopDate($row['Stop_date']);
            }

            $cnn->disconnect();
            return $reservationRecord;
        }
        catch (DBException $e) {
            throw $e;
        }
        catch (DBConnectionException $e) {
            throw $e;
        }
    }

    /**
     *Precondition:  Accepts a reservation object: The following member attribute must be set:
     *                - UserID
     *Postcondition: Find and return all reservations in the tReservation table
     *               by a UserID
     **/
    public static function findAllreservationRecord($Reservation) {
        try {
            $UserID = $Reservation->getUserID();

            $cnn = new DBConnection();

            $query = "SELECT * FROM tReservation
                          WHERE tReservation.user_id = '$UserID'";

            $result = $cnn->execute($query);

            while ($row = mysql_fetch_array($result)) {
                $reservationRecord = new Reservation();
                $reservationRecord->setReservationID($row['Reservation_id']);
                $reservationRecord->setResourceID($row['Resource_id']);
                $reservationRecord->setStartDate($row['Start_date']);
                $reservationRecord->setEndDate($row['End_date']);
                $reservationRecord->setUserID($row['User_id']);
                $reservationRecord->setReOccurrenceID($row['ReOccurrence_id']);
                $reservationRecord->setStopDate($row['Stop_date']);
                $reservationArray[] = $reservationRecord;
            }

            $cnn->disconnect();
            return $reservationArray;
        }
        catch (DBException $e) {
            throw $e;
        }
        catch (DBConnectionException $e) {
            throw $e;
        }
    }

    /**
     * Finds all the Reservations associated with the given Resource Id.
     *
     * @param $resourceId   The id from the specific resource record.
     * @return              Reservation[]. Returns an array of all
     *                      the Reservations associated to the given Resource Id.
     */
    public static function findAllReservationsByResourceId($resourceId) {
        try {
            $cnn = new DBConnection();
            $query = "SELECT * FROM tReservation
                          WHERE tReservation.Resource_id = '$resourceId'";
            $result = $cnn->execute($query);
            while ($row = mysql_fetch_array($result)) {
                $reservationRecord = new Reservation();
                $reservationRecord->setReservationID($row['Reservation_id']);
                $reservationRecord->setResourceID($row['Resource_id']);
                $reservationRecord->setStartDate($row['Start_date']);
                $reservationRecord->setEndDate($row['End_date']);
                $reservationRecord->setUserID($row['User_id']);
                $reservationRecord->setReOccurrenceID($row['ReOccurrence_id']);
                $reservationRecord->setStopDate($row['Stop_date']);
                $reservationArray[] = $reservationRecord;
            }
            $cnn->disconnect();
            return $reservationArray;
        }
        catch (DBException $e) {
            throw $e;
        }
        catch (DBConnectionException $e) {
            throw $e;
        }
    }

    /**
     * Checks if given resource id is available for reservation in a
     * specific date range.
     *
     * @param $resourceId   The id from the specific resource record.
     * @param $startDate    The startDate for the reservation.
     * @param $endDate      The endDate for the reservation.
     * @return              Trueor False. Returns true if the reservation is
     *                      valid for the date range given. Returns false if
     *                      the reservation is invalid for the date range given.
     */
     public static function isResourceReservationDateRangeValid ($resourceId, $startDate, $endDate) {
        try {

            $isResourceReservationDateRangeValid = false;

            $cnn = new DBConnection();

            $query = "SELECT * FROM tReservation
                      WHERE tReservation.Resource_id = '$resourceId'
                      AND ((tReservation.Start_date BETWEEN '$startDate' AND '$endDate')
                      OR (tReservation.End_date BETWEEN '$startDate' AND '$endDate'))";

            $result = $cnn->execute($query);

            $numRows = mysql_numrows($result);

            if ($numRows == 0) {
                $isResourceReservationDateRangeValid = true;
            }

            $cnn->disconnect();

            return $isResourceReservationDateRangeValid;

        }
        catch (DBException $e) {
            throw $e;
        }
        catch (DBConnectionException $e) {
            throw $e;
        }
    }

    /**
     * Checks if reoccurrent reservation is valid.
     *
     * @param $resourceId      The id from the specific resource record.
     * @param $startDate       The startDate for the reservation.
     * @param $reoccurrenceId  The endDate for the reservation.
     * @param $stopDate        The endDate for the reservation.
     * @return                 True or False. Returns true if the reservation is
     *                         valid for the date range given. Returns false if
     *                         the reservation is invalid for the date range given.
     */
     public static function isReoccurrentResourceReservationValid ($resourceId, $startDate,
             $endDate, $reoccurrenceId, $stopDate) {
        try {

            $resourceReservations = self::findAllReservationsByResourceId($resourceId);

            if (($reoccurrenceId == 1) || ($reoccurrenceId == 2) || ($reoccurrenceId == 3)) {

                $newReoccurrenceIncrement = self::getReoccurrenceIncrementString($reoccurrenceId);

                $newStartDate = $startDate;
                $newStopDate = $stopDate;
                for ($i = strtotime($newStartDate); $i <= strtotime($newStopDate); $i = strtotime(date("Y-m-d", $i) . $newReoccurrenceIncrement)) {
                    for ($j = 0; $j < count($resourceReservations); $j++) {
                        $tempReservation = $resourceReservations[$j];
                        if (($tempReservation->getReOccurrenceID() == 1) || ($tempReservation->getReOccurrenceID() == 2) || ($tempReservation->getReOccurrenceID() == 3)) {
                            $tempReoccurrenceIncrement = self::getReoccurrenceIncrementString($tempReservation->getReOccurrenceID());
                            $tempStartDate = $tempReservation->getStartDate();
                            $tempStopDate = $tempReservation->getStopDate();
                            for ($k = strtotime($tempStartDate); $k <= strtotime($tempStopDate); $k = strtotime(date("Y-m-d", $k) . $tempReoccurrenceIncrement)) {
                                if ($i == $k) {
                                    return false;
                                }
                            }
                        } else {
                            if ($i == strtotime($tempReservation->getStartDate())) {
                                return false;
                            }
                        }
                    }
                }

            } else {
                for ($i = 0; $i < count($resourceReservations); $i++) {
                    $tempReservation = $resourceReservations[$i];
                    if (($tempReservation->getReOccurrenceID() == 1) || ($tempReservation->getReOccurrenceID() == 2) || ($tempReservation->getReOccurrenceID() == 3)) {
                        $tempReoccurrenceIncrement = self::getReoccurrenceIncrementString($tempReservation->getReOccurrenceID());
                        $tempStartDate = $tempReservation->getStartDate();
                        $tempStopDate = $tempReservation->getStopDate();
                        for ($j = strtotime($tempStartDate); $j <= strtotime($tempStopDate); $j = strtotime(date("Y-m-d", $j) . $tempReoccurrenceIncrement)) {
                            if (((strtotime($startDate) >= $j) && (strtotime($startDate) <= $j)) ||
                                ((strtotime($endDate) >= $j) && (strtotime($endDate) <= $j)) ||
                                ((strtotime($startDate) <= $j) && (strtotime($endDate) >= $j)) ||
                                ((strtotime($startDate) <= $j) && (strtotime($endDate) >= $j))) {
                                return false;
                            }
                        }
                    } else {
                        if (((strtotime($startDate) >= strtotime($tempReservation->getStartDate())) && (strtotime($startDate) <= strtotime($tempReservation->getEndDate()))) ||
                            ((strtotime($endDate) >= strtotime($tempReservation->getStartDate())) && (strtotime($endDate) <= strtotime($tempReservation->getEndDate()))) ||
                            ((strtotime($startDate) <= strtotime($tempReservation->getStartDate())) && (strtotime($endDate) >= strtotime($tempReservation->getStartDate()))) ||
                            ((strtotime($startDate) <= strtotime($tempReservation->getEndDate())) && (strtotime($endDate) >= strtotime($tempReservation->getEndDate())))) {
                            return false;
                        }
                    }
                }
            }

            return true;

        }
        catch (DBException $e) {
            throw $e;
        }
        catch (DBConnectionException $e) {
            throw $e;
        }
    }

    private static function getReoccurrenceIncrementString ($reoccurrenceId) {
        $reoccurrenceIncrement = "";
        if ($reoccurrenceId == 1) {
            $reoccurrenceIncrement = " +1 day";
        } else if ($reoccurrenceId == 2) {
            $reoccurrenceIncrement = " +1 week";
        } else if ($reoccurrenceId == 3) {
           $reoccurrenceIncrement = " +1 month";
        }
        return $reoccurrenceIncrement;
    }

}

?>
